/*
 * 涉及相关文件：
 * /etc/hosts, /etc/services, /etc/gai.conf
 */

/* man getaddrinfo */
/* Client */
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

/* http://blog.sina.com.cn/s/blog_46d93f190100ojap.html */
#define BUF_SIZE 500    /* 这个长度是有讲究的 */

int
main(int argc, char *argv[])
{
    struct addrinfo  hints;
    struct addrinfo *result, *rp;
    int              sfd, s, j;
    size_t           len;
    ssize_t          nread;
    char             buf[BUF_SIZE];

    if (argc < 3) {
        fprintf(stderr, "Usage: %s host port msg...\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    /* Obtain address(es) matching host/port */

    memset(&hints, 0, sizeof(struct addrinfo));
    hints.ai_family = AF_UNSPEC;        /* Allow IPv4 or IPv6 */
    hints.ai_socktype = SOCK_DGRAM;     /* Datagram socket */
    hints.ai_flags = 0;
    hints.ai_protocol = 0;              /* Any protocol */

    s = getaddrinfo(argv[1], argv[2], &hints, &result);
    if (s != 0) {
        fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s));
        exit(EXIT_FAILURE);
    }

    /*
     * getaddrinfo return a list of address structures.
     * Try each address until we successfully connect(2).
     * If socket(2) (or connect(2)) fails, we (close the socket
     * and) try the next address.
     */

    for (rp = result; rp != NULL; rp = rp->ai_next) {
        sfd = socket(rp->ai_family, rp->ai_socktype,
                     rp->ai_protocol);
        if (sfd == -1)
            continue;

        if (connect(sfd, rp->ai_addr, rp->ai_addrlen) != -1)
            break;          /* Success */

        close(sfd);
    }

    if (rp == NULL) {       /* No address succeeded */
        fprintf(stderr, "Could not connect\n");
        exit(EXIT_FAILURE);
    }

    freeaddrinfo(result);   /* No longer needed */

    /*
     * Send remaining command-line arguments as separate
     * datagrams, and read response from server.
     */

    for (j = 3; j < argc; j++) {
        len = strlen(argv[j]) + 1;  /* +1 for terminating null byte */

        if (len + 1 > BUF_SIZE) {
            fprintf(stderr, "Ignoring long message in argument %d\n", j);
            continue;
        }

        if (write(sfd, argv[j], len) != len) {
            fprintf(stderr, "partial/failed write\n");
            exit(EXIT_FAILURE);
        }

        nread = read(sfd, buf, BUF_SIZE);
        if (nread == -1) {
            perror("read");
            exit(EXIT_FAILURE);
        }

        printf("Received %ld bytes: %s\n", (long)nread, buf);
    }

    exit(EXIT_SUCCESS);
}
/*
 * 参考资料：
 * http://blog.chinaunix.net/uid-20196318-id-172427.html
 * 如果你的应用程序需要使用主机名代替IP地址，或服务名代替端口号，
 * 你需要先把对应关系增加到对应的配置文件中，否则getaddrinfo会解析出错.
 */
